package algos;

import java.util.Iterator;

/**
 *
 * @author nicolas
 */
public class Backtracker<T> {
	
	public Solution<T> solve(Problem<T> problem, GameController<T> gc) {
		ContextStack<T> contextStack = problem.getContextStack();
		T context = contextStack.currentContext();
		Iterator<Action<T>> ai = null;
		Action<T> action;
		
		while(!gc.isComplete(contextStack)) {
			context = contextStack.currentContext();
			if (gc.isCorrect(context) && (ai==null || ai.hasNext())) {
				ai = contextStack.currentActionsIterator();
				action = ai.next();
				context = action.applyOn(contextStack);
				ai = gc.getActions(context).iterator();
				contextStack.push(context, ai);
//				System.out.println("push");
			} else {
				contextStack.pop();
				ai = contextStack.currentActionsIterator();
//				System.out.println("pop");
			}
			
			System.out.println(context);
		}
		
		return new Solution<T>(contextStack.currentContext());
	}
	
}
